﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

using XBS.Model;
using XBS.ViewModel;
using XBS.Converter;
using System.IO.IsolatedStorage;

namespace XBS
{
    public partial class StoryPage : PhoneApplicationPage
    {
        private Story story;
        private int paragraphPosition = 0;

        public StoryPage()
        {
            InitializeComponent();

            StoryDetailOnPage.BookmarkClick += StoryDetailOnPage_BookmarkClick;
            StoryDetailOnPage.ListLoaded += StoryDetailOnPage_ListLoaded;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string storyIndex, paragraphIndex;
            NavigationContext.QueryString.TryGetValue("story", out storyIndex);
            NavigationContext.QueryString.TryGetValue("paragraph", out paragraphIndex);

            try
            {
                paragraphPosition = int.Parse(paragraphIndex);
            }
            catch (ArgumentNullException) { }
            catch (FormatException) { }
            catch (OverflowException) { }
            
            story = App.ViewModel.GetStory(storyIndex);

            if (story != null)
            {
                LayoutRoot.DataContext = story;
                foreach (Para paragraph in story.ListParas)
                {
                    paragraph.Foreground = App.ViewModel.GetTextColor();
                    paragraph.Background = App.ViewModel.GetBackgroundColor();
                    paragraph.Fontsize = App.ViewModel.GetFontsize();
                }

                if (story.ListParas.Count > 0)
                {
                    story.ListParas.ElementAt(0).ImgSrc = story.ImgSrc;
                }

                StoryDetailOnPage.DataContext = story.ListParas;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            App.ViewModel.AddNewRecentStory(story);

            // save the recent stories index
            if (IsolatedStorageSettings.ApplicationSettings.Contains(VM.KEY_RECENT_STORIES_INDEX))
            {
                IsolatedStorageSettings.ApplicationSettings[VM.KEY_RECENT_STORIES_INDEX] = App.ViewModel.ListRecentStories;
            }
            else
            {
                IsolatedStorageSettings.ApplicationSettings.Add(VM.KEY_RECENT_STORIES_INDEX, App.ViewModel.ListRecentStories);
            }
        }

        void StoryDetailOnPage_BookmarkClick(object sender, EventArgs e)
        {
            ListBoxItem selected = StoryDetailOnPage.ListParagraph.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            Para paragraph = (Para)selected.Content;

            App.ViewModel.AddNewBookmarkParagraph(
                new Bookmark
                {
                    ParagraphIndex = paragraph.Index,
                    StoryIndex = story.Index,
                    ParagraphName = paragraph.Paragraph,
                    StoryName = story.Name
                });

            // save the bookmark paragraph index
            if (IsolatedStorageSettings.ApplicationSettings.Contains(VM.KEY_BOOKMARKED_PARAGRAPH))
            {
                IsolatedStorageSettings.ApplicationSettings[VM.KEY_BOOKMARKED_PARAGRAPH] = App.ViewModel.ListBookmarks;
            }
            else
            {
                IsolatedStorageSettings.ApplicationSettings.Add(VM.KEY_BOOKMARKED_PARAGRAPH, App.ViewModel.ListBookmarks);
            }
        }

        void StoryDetailOnPage_ListLoaded(object sender, EventArgs e)
        {
            if (story != null && story.ListParas.Count > paragraphPosition)
            {
                StoryDetailOnPage.ListParagraph.ScrollIntoView(story.ListParas[paragraphPosition]);
                StoryDetailOnPage.UpdateLayout();
            }
        }

        private void SettingBtn_Click(object sender, EventArgs e)
        {
            Uri settingPage = new Uri("/SettingPage.xaml", UriKind.Relative);
            NavigationService.Navigate(settingPage);
        }

        private void PinBtn_Click(object sender, EventArgs e)
        {
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("story=" + story.Index));
            if (TileToFind == null)
            {
                StandardTileData NewTileData = new StandardTileData
                {
                    BackgroundImage = new Uri(story.ImgSrc, UriKind.Relative),
                    Title = story.Name
                };

                ShellTile.Create(new Uri("/StoryPage.xaml?story=" + story.Index, UriKind.Relative), NewTileData);
            }
            else
            {
                MessageBox.Show("The story is already pinned to screen");
            }
        }

    }
}